package com.DHH.wx.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * JAVA只需要使用apiclient_cert.p12即可，如果使用JAVA语言进行开发的可以忽略其余三个pem格式的文件。
 */
public class ClientCustomSSL {

    public void CertificateTrust()  throws Exception {
    	//指定读取证书格式为PKCS12
        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
        
      //读取本机存放的PKCS12证书文件
        FileInputStream instream = new FileInputStream(new File("C:/apiclient_cert.p12"));
        
        try {
        	//指定PKCS12的密码(商户ID)
            keyStore.load(instream, "1484560402".toCharArray());
        } finally {
            instream.close();
        }

        // 相信自己，所有的自签名证书的CA
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, "1484560402".toCharArray())
                .build();
        // 只允许TLSv1协议，指定TLS版本
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        
        //设置httpclient的SSLSocketFactory
        CloseableHttpClient httpclient = HttpClients.custom()
        .setSSLSocketFactory(sslsf)
        .build();
        
         try {

            HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

            System.out.println("executing request" + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println("----------------------------------------");
                
               if (entity != null) {
                   // System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        System.out.println(text);
                    }
                   
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
    /**
    * https双向签名认证，用于支付申请退款
    * 
    * */
        public static String payHttps(String url,String data) throws Exception {
        //商户id
        String MCH_ID ="1484560402";
        //指定读取证书格式为PKCS12
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        
        //读取本机存放的PKCS12证书文件
        FileInputStream instream = new FileInputStream(new File("c:/apiclient_cert.p12"));
        try {
        //指定PKCS12的密码(商户ID)
        keyStore.load(instream, MCH_ID.toCharArray());
        } finally {
        instream.close();
        }
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, MCH_ID.toCharArray()).build();
        //指定TLS版本
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,new String[] { "TLSv1" },null,
        SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        //设置httpclient的SSLSocketFactory
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();


            try {
            HttpPost httpost = new HttpPost(url); // 设置响应头信息
            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
                CloseableHttpResponse response = httpclient.execute(httpost);
                try {
                    HttpEntity entity = response.getEntity();

                    String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                    EntityUtils.consume(entity);
                    
                    return jsonStr;
                   
                } finally {
                    response.close();
                }
            } finally {
                httpclient.close();
            }
        }
}


